<template>
  <el-row class="user-info-form" type="flex" justify="center">
      <el-col>
        <div class="asset-info-form">
          <el-form label-width="150px" :model="areaBaseInfoForm" :rules="areaBaseInfoFormRules" ref="areaBaseInfoForm" @submit.native.prevent>
            <el-form-item label="名称："  prop='name'>
              <el-input
                v-model="areaBaseInfoForm.name"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="所属消防大队："  prop='belongsFireBrigade'>
              <el-input
                v-model="areaBaseInfoForm.belongsFireBrigade"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="图片：" prop='pictures'>
              <el-upload
                :action="QINIUUPLOADURL"
                :multiple="false"
                ref="upload"
                list-type="picture-card"
                :data="qiniuData"
                :on-success="handleAvatarSuccess"
                :on-remove="handleRemovePic"
                :on-error="handleError"
                :before-upload="beforeAvatarUpload"
                :on-preview="$imgPreview"
                :file-list="qiniuData.fileList"
                :limit="1"
                :on-exceed="handleExceed"
                accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label-width="0" class="verifyidentity-button">
              <el-button @click.stop="closeFun(false)" round>取消</el-button>
              <el-button type="primary" @click="saveAreaInfo('areaBaseInfoForm')" round>保存</el-button>
            </el-form-item>
          </el-form>

        </div>
      </el-col>
  </el-row>
</template>
<script>
import { qnToken} from '@/api/api'
import util from '@/utils/util'
import { updateAreaCounty } from '@/api/sysConfig'
export default {
    name: 'AreaManageBaseInfo',
    props: {
      areaInfo: {
          type: Object
      },
      closeFun: {
          type: Function,
          required: true
      },
    },
  data(){
    return {
      qiniuData:{//上传图片携带的参数
        token : "",
        key : "",
        fileList:[],
      },
      // 表单数据
      areaBaseInfoForm: {
        id: '',
        name: '',
        belongsFireBrigade: ''
      },
      // 表单校验
      areaBaseInfoFormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'change' }
        ],
        belongsFireBrigade: [
          { required: true, message: '请输入所属消防大队', trigger: 'change' }
        ],
      },

    }
  },

  created() {
    let that = this
    that.getToken()
    // 如果有历史值，设置回显
    if (that.areaInfo.id) {
      that.areaBaseInfoForm.id = that.areaInfo.id
      that.areaBaseInfoForm.name = that.areaInfo.name
      that.areaBaseInfoForm.belongsFireBrigade = that.areaInfo.belongsFireBrigade
      // 设置上传图片初始值
      that.areaInfo.url ? $.each(that.areaInfo.url.split(','), (index, url) => {
        that.qiniuData.fileList.push({
          name: that.areaInfo.id + index,
          url: url
        })
      }) : ''
    }
  },

  methods: {
    getToken(){  //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token= result.data
      })
    },
    beforeAvatarUpload: function(file){//重命名和校验
      var fielLocal = file.name.split(".")
      var fielType = "." + fielLocal[fielLocal.length-1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'assesImg'+'_'+new Date().getTime()+fielType
      //this.qiniuData.key = file.name;
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!")
        return false;
      }
      if (!isLt20M) {
        this.$message.error("图片大小不能超过 20MB!")
        return false;
      }
    },
    handleAvatarSuccess: function(res, file, fileList) {//上传成功
      this.qiniuData.fileList = fileList
    },
    handleRemovePic: function(file, fileList) {//删除成功
      this.qiniuData.fileList = fileList
    },
    handleError: function(res) {
      this.$message({
        message: "上传失败",
        duration: 2000,
        type: "warning"
      })
    },
    handleExceed(files, fileList) {//文件超出个数限制时的钩子
      this.$message.warning(`只能上传1张图片！`)
    },
    // 保存
    saveAreaInfo(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      let type = 1
      let parames = {}
      // 校验表单
      that.$refs[formName].validate((valid) => {
        if(valid) {
          parames = {
            name: that.areaBaseInfoForm.name,
            url: util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString(),
            belongsFireBrigade: that.areaBaseInfoForm.belongsFireBrigade,
            id: that.areaInfo.id,
            parentId:that.areaInfo.parentId,
            level:that.areaInfo.level
          }
          if(that.areaInfo.id==null){
              parames.id = 0
              parames.level = 3
          }

          // if(parames.url==null || parames.url==""){
          //   this.$message({
          //     message: '请上传行政区图片',
          //     type: 'warning'
          //   })
          //   return
          // }

          // 调用保存接口
          updateAreaCounty(parames).then(res => {
            if(res.status === 200) {
              that.$message({
                message: '保存成功！',
                type: 'success'
              })
              // 关闭弹框
              that.closeFun(true)
            } else {
              that.$message({
                message: '保存失败！',
                type: 'warning'
              })
            }
          })
        } else {
          return false
        }
      })
    },
  }
}
</script>
